package top.haijunit.springboot.bucket.springsecurity02.security;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import top.haijunit.springboot.bucket.springsecurity02.service.UserService;
import top.haijunit.mark.common.core.utils.JwtUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @Author 百旺张
 * @Date 2021/11/11
 * @Description
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private UserService userService;

    public TokenAuthFilter(AuthenticationManager authenticationManager, UserService userService) {
        super(authenticationManager);
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文中
        if (authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // 从header获取token
        String token = Optional.ofNullable(request.getHeader(JwtUtil.tokenName)).orElse(request.getParameter(JwtUtil.tokenName));
        if (StrUtil.isNotBlank(token)) {
            // 从token获取用户名
            String username = JwtUtil.getUsernameFromToken(token);
            UserDetails userDetails = userService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, token, userDetails.getAuthorities());
            authenticationToken.setDetails(userDetails);
            return authenticationToken;
        }
        return null;
    }
}
